#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"

// 辅助函数：将字符转换为十六进制字符串
void charToHex(char c, char *hexStr) {
    sprintf(hexStr, "%02X", (unsigned char)c);
}

// 主函数：将字符数组转换为十六进制表示的JSON字符串
char* charArrayToHexJson(const char* charArray) {
    cJSON *root = cJSON_CreateObject();
    if (root == NULL) {
        return NULL;
    }

    // 假设你要将整个字符数组转换为十六进制形式放入msg字段
    size_t len = strlen(charArray);
    char *hexStr = (char *)malloc(len * 2 + 1);
    if (hexStr == NULL) {
        cJSON_Delete(root);
        return NULL;
    }
    hexStr[0] = '\0';
    for (size_t i = 0; i < len; i++) {
        char hex[3];
        charToHex(charArray[i], hex);
        strcat(hexStr, hex);
    }

    cJSON_AddNumberToObject(root, "conn_type", 1);
    cJSON_AddStringToObject(root, "id", "5858");
    cJSON_AddStringToObject(root, "msg", hexStr);

    char *jsonStr = cJSON_Print(root);
    cJSON_Delete(root);
    free(hexStr);
    return jsonStr;
}

int main() {
    const char* charArray = "124XXabcd";
    char* jsonStr = charArrayToHexJson(charArray);
    if (jsonStr != NULL) {
        printf("%s\n", jsonStr);
        free(jsonStr);
    }
    return 0;
}